package cn.edu.hbpu.dto;

import cn.edu.hbpu.entity.sys.SysUser;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lcy
 * @date 2022/8/5 16:09
 * @description 作为UserDetailsService的返回值。存入redis的对象
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdminUser implements UserDetails {

    /**
     * 存储数据库中查询到的用户信息
     */
    @JsonProperty("sysUser")
    private SysUser sysUser;

    /**
     * 数据库中查询出来的权限
     */
    @JsonProperty("permissions")
    private List<String> permissions;

    /**
     * SpringSecurity需要的权限列表的类型。保存为成员变量是为了不要每次都将permissions转为authoritiesSet
     * JSONField(serialize = false) 因为redis不能将这个对象序列化到流当中，会报错，所以不进行序列化。只需要将permissions序列化存储就好
     */
    @JSONField(serialize = false)
    private Set<SimpleGrantedAuthority> authorities;

    public AdminUser(SysUser sysUser) {
        this.sysUser = sysUser;
    }

    public AdminUser(SysUser sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    /**
     * 在此处返回从数据库查询到的权限
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 把permission中的String类型的权限封装成SimpleGrantedAuthority的实现类对象
        if (authorities != null) {
            return authorities;
        }
        authorities = new HashSet<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        // 流写法 authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        return authorities;
    }

    /**
     * 需要在此处返回从数据库中查询到的密码
     *
     * @return
     */
    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    /**
     * 需要在此处返回从数据库中查询到的用户名
     *
     * @return
     */
    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
